package com.sxhalo.fsms.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sxhalo.fsms.domain.FactDrawingInfo;
import com.sxhalo.fsms.domain.LogDownload;
import com.sxhalo.fsms.domain.SysAttachments;
import com.sxhalo.fsms.domain.SysDeviceAttr;
import com.sxhalo.fsms.service.IFactDrawingInfoService;
import com.sxhalo.fsms.service.ILogDownloadService;
import com.sxhalo.fsms.service.ISysAttachmentsService;
import com.sxhalo.fsms.service.ISysDeviceAttrService;
import com.sxhalo.fsms.util.CookieUtils;
import com.sxhalo.fsms.util.TokenUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



import net.coobird.thumbnailator.Thumbnails;

@Controller
public class UploadController extends  BaseController {


	@Autowired
	private ISysAttachmentsService attachmentService;

	@Autowired
	private IFactDrawingInfoService drawingInfoService;

	@Autowired
	private ILogDownloadService downloadService;

	@Autowired
	private ISysDeviceAttrService attrService;



	//绑定文件上传路径到uploadPath
	@Value("${web.upload-path}")
	private String uploadPath;

	@RequestMapping(value = "/img/{picCode}", method = RequestMethod.GET)
	public void openPicCode(@PathVariable("picCode") String picCode, HttpServletRequest request,
			HttpServletResponse response) {
		openPicture(picCode, null, "picture",request, response);
	}

	@RequestMapping(value = "/img/{picCode}/{type}", method = RequestMethod.GET)
	public void openPicType(@PathVariable("picCode") String picCode, @PathVariable("type") String type,
			HttpServletRequest request, HttpServletResponse response) {
		openPicture(picCode, type, "picture",request, response);
	}

	@ResponseBody
	@RequestMapping(value = "/api/imageUpload", method = RequestMethod.POST)
	public SysAttachments imageUpload(MultipartFile file,String type,String id, HttpServletRequest request) {
		if (file != null && file.getSize() > 0) {
			return savePicture(file, request,type,id);
		}
		return null;
	}



	private SysAttachments savePicture(MultipartFile file, HttpServletRequest request, String type,String id ) {
		String realPath = uploadPath + "picture/";
		try {
			String fileName = file.getOriginalFilename();
			String picCode = UUID.randomUUID().toString();;
			File localFile = new File(realPath + picCode + ".jpeg");
			File parentFile = localFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			BufferedImage image = ImageIO.read(file.getInputStream());
			if (file.getSize() > 10485760 || image.getWidth() > 1920 || image.getHeight() > 1080) {
				Thumbnails.of(file.getInputStream()).size(1920, 1080).outputQuality(0.8).outputFormat("jpeg").toFile(localFile);
			} else {
				file.transferTo(localFile);
			}
			// 保存上传记录
			if (!"".equals(picCode)) {
				Timestamp nowTime = new Timestamp(System.currentTimeMillis());
				SysAttachments sa=new SysAttachments();
				sa.setRelativePath("/img/" + picCode);
				sa.setPath(realPath + picCode + ".jpeg");
				sa.setTitle(fileName);
				sa.setFileType("jpeg");
				sa.setAttachCode(picCode);
				sa.setUploadTime(nowTime);
				sa.setUpdateTime(nowTime);
				//sa.setUploadUser(userCode);
				attachmentService.insertSelective(sa);
				updateData( type, id,  picCode);
				return sa;
			}


		} catch (Exception e) {
			System.out.println("MultipartFile上传报错！");
			e.printStackTrace();
		}
		return null;
	}


	private void updateData(String type,String id, String picCode){
		if(!isBlank(type)&&!isBlank(id)){
			if(type.equals("attr")){
				SysDeviceAttr record =new SysDeviceAttr();
				record.setAttrId(Integer.parseInt(id));
				record.setAttrImg(picCode);
				attrService.updateByPrimaryKeySelective(record);
			}

		}

	}


	/**imgType 图片类型 "picture" 图片   "drawing" 图纸
	 * */
	private void openPicture(String picCode, String type,String imgType, HttpServletRequest request, HttpServletResponse response) {
		try {
			String realPath = uploadPath +imgType+ "/";
			String filePath = realPath + picCode + ".jpeg";

			File localFile = new File(filePath);
			if (localFile.exists()) {
				if (type != null) {
					if ("big".equals(type.toLowerCase())) {
						Thumbnails.of(filePath).size(800, 600).toOutputStream(response.getOutputStream());
					}
					if ("small".equals(type.toLowerCase())) {
						Thumbnails.of(filePath).size(160, 120).toOutputStream(response.getOutputStream());
					}
					if ("normal".equals(type.toLowerCase())) {
						Thumbnails.of(filePath).size(640, 480).toOutputStream(response.getOutputStream());
					}
				} else {
					Thumbnails.of(filePath).scale(1).toOutputStream(response.getOutputStream());
				}
			} else {
				System.out.println("Could not find file:" + filePath);
				// 在此根据类型可以取默认图片
			}
		} catch (IOException e) {
			String exceptionSimpleName = e.getClass().getSimpleName();
			if (!"ClientAbortException".equals(exceptionSimpleName)) {
				exceptionSimpleName = e.getCause().getClass().getSimpleName();
			}
			if ("ClientAbortException".equals(exceptionSimpleName)) {
				// 客户端断开连接不做处理
			} else {
				System.out.println("读取文件" + picCode + "报错！");
				e.printStackTrace();
			}
		}
	}



	private void openFile(String filePath, HttpServletRequest request, HttpServletResponse response) {
		try {

			//读取本地录音输入流
			FileInputStream inputStream = new FileInputStream(filePath);
			int i = inputStream.available();
			//byte数组用于存放图片字节数据
			byte[] buff = new byte[i];
			inputStream.read(buff);
			//记得关闭输入流
			inputStream.close();
			//设置发送到客户端的响应内容类型
//			response.setContentType("audio/wav");
			OutputStream out = response.getOutputStream();
			out.write(buff);
			out.close();


		} catch (IOException e) {

		} finally{



		}
	}




	public String getUploadPath(HttpServletRequest request) {
		ServletContext servletContext = request.getSession().getServletContext();

		String uploadPath = servletContext.getRealPath("/").split("webapps")[0] + "upload\\";
		return uploadPath;
	}


	@ResponseBody
	@RequestMapping(value = "/api/fileUpload", method = RequestMethod.POST)
	public SysAttachments fileUpload(MultipartFile file, HttpServletRequest request) {
		if (file != null && file.getSize() > 0) {
			if(file.getOriginalFilename().endsWith(".png")||file.getOriginalFilename().endsWith(".jpg")){
				return savePicture(file, request,null,null);
			}else{
				return saveDocument(file,"attachments", request);
			}
		}
		return null;
	}







	public  SysAttachments saveDocument  (MultipartFile file,String packageName , HttpServletRequest request) {
		Integer userId = null;
		String token = CookieUtils.getCookieValue(request, "token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		String realPath = (uploadPath==null?"":uploadPath) + packageName+"/";
		try {
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String fileCode = UUID.randomUUID().toString();
			File localFile = new File(realPath + fileCode + "." + suffix);
			File parentFile = localFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			//文件另存为
			file.transferTo(localFile);
			// 保存上传记录
			if (!"".equals(fileCode)) {
				Timestamp nowTime = new Timestamp(System.currentTimeMillis());
				SysAttachments record = new SysAttachments();
				record.setRelativePath("/attachments/" + fileCode+  "." + suffix);
				record.setPath(realPath + fileCode +  "." + suffix);
				record.setAttachCode(fileCode);
				record.setTitle(fileName);
				record.setFileType(suffix);
				record.setUploadTime(nowTime);
				record.setUpdateTime(nowTime);
				record.setUploadUser(userId);
				int count = attachmentService.updateByPrimaryKeySelective(record);
				if (count == 0) {
					attachmentService.insertSelective(record);
				}
//				System.out.println("000");
//				if(suffix.equals("dwg")){
//					ExecutorService executor= Executors.newFixedThreadPool(1);
//					CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
//						CADFileUtil.CADFileToPDF(record.getPath(),realPath + fileCode +  ".pdf");
//						return "success";
//					},executor);
//				}
//				System.out.println(111);
				return record;
			}
		} catch (Exception e) {
			System.out.println("MultipartFile上传报错！");
			e.printStackTrace();
		}
		return null;
	}





	//上传图纸
	@ResponseBody
	@RequestMapping(value = "/api/drawingfileUpload", method = RequestMethod.POST)
	public FactDrawingInfo drawingfileUpload(MultipartFile file,String  id,String typeId, HttpServletRequest request) {
		Integer userId = null;
		String token = CookieUtils.getCookieValue(request, "token");
		if (token != null) {
			 userId = TokenUtil.getUserId(token);
		}
		String realPath = uploadPath + "drawing/";
		try {
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		//	String suffix = "jpeg";
			if(suffix.equals("jpg")||suffix.equals("png")){
				suffix = "jpeg";
			}
			String fileCode = UUID.randomUUID().toString();
//			if(id!=null&&!id.equals("")){
//				fileCode=id;
//			}
			File localFile = new File(realPath + fileCode + "." + suffix);
			File parentFile = localFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			//文件另存为
			file.transferTo(localFile);
			// 保存上传记录
			if (!"".equals(fileCode)) {
				Timestamp nowTime = new Timestamp(System.currentTimeMillis());
				FactDrawingInfo record = new FactDrawingInfo();
				record.setRelativePath("/drawing/" + fileCode+  "." + suffix);
				record.setFilePath(realPath + fileCode +  "." + suffix);
				record.setPath("/drawing/" + fileCode);
				record.setSuffix(suffix);
				record.setTypeId(typeId);
				record.setSize( (int)file.getSize() );
				record.setUploadTime(nowTime);
				record.setDrawingName(fileName);
				record.setDrawingName(fileName);
				record.setUploadUser(userId);
				record.setCreateTime(nowTime);
				record.setDeleteFlag(0);
				//record.setUseState(useState==null?0:useState);
				record.setUpdateTime(nowTime);
				record.setDrawingId(fileCode);
				drawingInfoService.insertSelective(record);
				if (id != null&&!id.equals("")) {
					drawingInfoService.deleteByPrimaryKey(id);
				}
//
//				else{
//					record.setDrawingId(id);
//					drawingInfoService.updateByPrimaryKeySelective(record);
//				}
				return record;
			}
		} catch (Exception e) {
			System.out.println("MultipartFile上传报错！");
			e.printStackTrace();
		}
		return null;

	}

	//打开图纸
	@RequestMapping(value = "/drawing/{picCode}", method = RequestMethod.GET)
	public void openDrawing(@PathVariable("picCode") String picCode, HttpServletRequest request,
							HttpServletResponse response) {
		FactDrawingInfo record =drawingInfoService.selectByPrimaryKey(picCode);
		if(record.getFilePath().indexOf(".jpeg")==-1){
			openFile(record.getFilePath(),request, response);
		}else{
			openPicture(picCode, null,"drawing" ,request, response);
		}


	}


	@RequestMapping(value = "/drawing/download/{drawingId}", method = RequestMethod.GET)
	public void fileDownload(@PathVariable("drawingId") String drawingId, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		Integer userId = null;
		String token = CookieUtils.getCookieValue(request, "token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		FactDrawingInfo record = drawingInfoService.selectByPrimaryKey(drawingId);
		//获取文件名称下载
		if (record != null) {
			File localFile = new File(record.getFilePath());

			if (localFile.exists()) {
				InputStream is = new FileInputStream(record.getFilePath());
				String filename = URLEncoder.encode(record.getDrawingName(), "UTF-8");
				// 设置response参数，可以打开下载页面
				response.reset();
				response.setContentType("application/octet-stream;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + filename);
				ServletOutputStream out = response.getOutputStream();
				BufferedInputStream bis = null; // 创建了一个内部缓冲区数组
				BufferedOutputStream bos = null;
				try {
					bis = new BufferedInputStream(is);
					bos = new BufferedOutputStream(out);
					byte[] buff = new byte[2048];
					int bytesRead;
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
						bos.write(buff, 0, bytesRead);
					}
					LogDownload download =new LogDownload();
					download.setUserId(userId);
					download.setLogType("图纸");
					download.setFileName(record.getDrawingName());
					download.setFileSize(record.getSize());
					download.setDownloadTime(new Date());
					download.setStatus(0);
					downloadService.insertSelective(download);

				} catch (final IOException e) {
					throw e;
				} finally {
					if (bis != null)
						bis.close();
					if (bos != null)
						bos.close();
				}
			}else{
				response.setStatus(404);
		 	throw new RuntimeException("文件不存在..");
			}
		}
	}


	@RequestMapping(value = "/attachments/download/{attachCode}", method = RequestMethod.GET)
	public void attachmentsDownload(@PathVariable("attachCode") String attachCode, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		Integer userId = null;
		String token = request.getHeader("x-auth-token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		SysAttachments record = attachmentService.selectByPrimaryKey(attachCode);
		//获取文件名称下载
		if (record != null) {
			File localFile = new File(record.getPath());

			if (localFile.exists()) {
				InputStream is = new FileInputStream(record.getPath());
				String filename = URLEncoder.encode(record.getTitle(), "UTF-8");
				// 设置response参数，可以打开下载页面
				response.reset();
				response.setContentType("application/octet-stream;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + filename);
				ServletOutputStream out = response.getOutputStream();
				BufferedInputStream bis = null; // 创建了一个内部缓冲区数组
				BufferedOutputStream bos = null;
				try {
					bis = new BufferedInputStream(is);
					bos = new BufferedOutputStream(out);
					byte[] buff = new byte[2048];
					int bytesRead;
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
						bos.write(buff, 0, bytesRead);
					}
					LogDownload download =new LogDownload();
					download.setUserId(userId);
					download.setLogType("附件");
					download.setFileName(record.getTitle());
					download.setFileSize(is.available());
					download.setDownloadTime(new Date());
					download.setStatus(0);
					downloadService.insertSelective(download);

				} catch (final IOException e) {
					throw e;
				} finally {
					if (bis != null)
						bis.close();
					if (bos != null)
						bos.close();
				}
			}
		}
	}
}
